/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CreateUsuarioDialog.java
 *
 * Created on 20/10/2011, 23:14:56
 */
package br.com.mocamorena.view.dialog;

import br.com.mocamorena.control.ControleUsuario;
import br.com.mocamorena.exception.InputValidationException;
import br.com.mocamorena.exception.PersistenciaException;
import br.com.mocamorena.model.Usuario;
import br.com.mocamorena.view.ErrorsList;
import br.com.mocamorena.view.StateEntityWindow;
import br.com.mocamorena.view.UserError;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Iterator;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

/**
 *
 * @author Diego
 */
public class CreateUsuarioDialog extends javax.swing.JDialog {

    private Usuario usuario;
    private final static String titleWindow = "Usuário";
    private StateEntityWindow stateEntity;

    public CreateUsuarioDialog(java.awt.Frame parent, boolean modal, StateEntityWindow stateEntity) {
        super(parent, modal);
        initComponents();
        this.stateEntity = stateEntity;
        setTitle(titleWindow + stateEntity);
        setLocationRelativeTo(null);
        organizeWindow();
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cabecalhoPanel = new br.com.mocamorena.view.panel.CabecalhoPanel();
        jLabel1 = new javax.swing.JLabel();
        nomeField = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        confirmarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        nomeErrorLabel = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        loginField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        senhaField = new javax.swing.JPasswordField();
        loginErrorLabel = new javax.swing.JLabel();
        senhaErrorLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Nome:");

        confirmarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/accept.png"))); // NOI18N
        confirmarButton.setText("Confirmar");
        confirmarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmarButtonActionPerformed(evt);
            }
        });

        cancelarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/cross.png"))); // NOI18N
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });

        nomeErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/exclamation.png"))); // NOI18N

        jLabel2.setText("Login:");

        jLabel3.setText("Senha:");

        loginErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/exclamation.png"))); // NOI18N

        senhaErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/mocamorena/resources/exclamation.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(cabecalhoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(71, 71, 71)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(loginField)
                                    .addComponent(nomeField, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(loginErrorLabel)
                                    .addComponent(nomeErrorLabel)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(senhaField, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(senhaErrorLabel)))))
                .addContainerGap(22, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(122, Short.MAX_VALUE)
                .addComponent(confirmarButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelarButton)
                .addGap(78, 78, 78))
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(cabecalhoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nomeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nomeErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(loginField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2))
                    .addComponent(loginErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(senhaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(senhaErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(confirmarButton)
                    .addComponent(cancelarButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelarButtonActionPerformed

    private void confirmarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmarButtonActionPerformed
        try {
            validateUserInput();
            ControleUsuario controle = new ControleUsuario();
            Usuario usuario = getUsuario();
            if (getStateEntity() == StateEntityWindow.NEW) {
                controle.inserir(usuario);
                
                /* Caso queira evitar login duplicado descomentar esse bloco
                if (!usuarioService.isLoginInUse(usuario.getLogin())) {
                    usuarioService.inserir(usuario);
                } else {
                    JOptionPane.showMessageDialog(this, "O login informado já está em uso, "
                            + "escolha outro diferente.", "Mensagem do sistema", 2);
                    loginField.requestFocus();
                    loginField.selectAll();
                    return;
                }
                */
            }
            dispose();
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        } catch (InputValidationException ivex) {
            JOptionPane.showMessageDialog(null, "Erros foram encontrados.", "Mensagem do sistema", JOptionPane.ERROR_MESSAGE);
            ErrorsList errorsList = ivex.getErrorsList();
            for (Iterator<UserError> it = errorsList.iterator(); it.hasNext();) {
                UserError userError = it.next();
                showErrorLabel(userError);
            }
        }
    }//GEN-LAST:event_confirmarButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println(ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                CreateUsuarioDialog dialog = new CreateUsuarioDialog(new javax.swing.JFrame(), true, StateEntityWindow.NEW);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private br.com.mocamorena.view.panel.CabecalhoPanel cabecalhoPanel;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JButton confirmarButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel loginErrorLabel;
    private javax.swing.JTextField loginField;
    private javax.swing.JLabel nomeErrorLabel;
    private javax.swing.JTextField nomeField;
    private javax.swing.JLabel senhaErrorLabel;
    private javax.swing.JPasswordField senhaField;
    // End of variables declaration//GEN-END:variables

    private Usuario getUsuario() {
        if (usuario == null) {
            usuario = new Usuario();
        }
        usuario.setBloqueado(cabecalhoPanel.isBloqueado());
        usuario.setNome(nomeField.getText().toUpperCase());
        usuario.setLogin(loginField.getText());
        usuario.setSenha(String.valueOf(senhaField.getPassword()));
        return usuario;
    }

    private void organizeWindow() {
        if (getStateEntity() == StateEntityWindow.NEW) {
            cabecalhoPanel.isEnabledComponentBloqueado(false);
        }
        isShowErrorsLabel(false);
    }

    public StateEntityWindow getStateEntity() {
        return stateEntity;
    }

    private void validateUserInput() throws InputValidationException {
        isShowErrorsLabel(false);
        ErrorsList errorsList = new ErrorsList();
        if (nomeField.getText().isEmpty()) {
            errorsList.addError(new UserError(nomeErrorLabel, "O nome do usuário não foi informado."));
        }
        if (loginField.getText().isEmpty()) {
            errorsList.addError(new UserError(loginErrorLabel, "O login do usuário não foi informado."));
        }
        if ((senhaField.getPassword().length < 3) || (senhaField.getPassword().length > 12)) {
            errorsList.addError(new UserError(senhaErrorLabel, "A senha do usuário deve ter entre 3 e 12 dígitos."));
        }
        if (errorsList.countErrors() > 0) {
            throw new InputValidationException(errorsList);
        }
    }

    private void isShowErrorsLabel(boolean show) {
        nomeErrorLabel.setVisible(show);
        loginErrorLabel.setVisible(show);
        senhaErrorLabel.setVisible(show);
    }

    private void showErrorLabel(UserError userError) {
        userError.getLabel().setVisible(true);
    }

    public Usuario objetoUsuario() {
        return usuario;
    }

    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                cancelarButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }
}
